package com.hwadee.backend.controller;

import com.hwadee.backend.entity.Authorize;
import com.hwadee.backend.entity.Result;
import com.hwadee.backend.entity.AuthorizeRequest.AuthorizationLookRequest;
import com.hwadee.backend.entity.AuthorizeRequest.AuthorizationUpdateRequest;
import com.hwadee.backend.entity.AuthorizeRequest.AuthorizationDeleteRequest;
import com.hwadee.backend.service.AuthorizeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/authorizations")
public class AuthorizeController {
    private static final Logger log = LoggerFactory.getLogger(AuthorizeController.class);

    @Autowired
    private AuthorizeService authorizeService;
    @Autowired
    private DataSourceTransactionManagerAutoConfiguration dataSourceTransactionManagerAutoConfiguration;

    /**
     * 获取用户的授权列表
     */
    @GetMapping("/user/{userId}")
    public Result getUserAuthorizations(@PathVariable Integer userId) {
        return Result.success(authorizeService.getAuthorizationsByUserId(userId));
    }

    /**
     * 获取授权详情
     */
    @GetMapping("/{authorizationId}")
    public Result getAuthorizationDetail(@PathVariable Integer authorizationId) {
        try {
            Authorize authorize = authorizeService.getAuthorizationById(authorizationId);
            if (authorize == null) {
                return Result.error("授权记录不存在");
            }
            return Result.success(authorize);
        } catch (Exception e) {

            log.error("获取授权详情失败", e);
            return Result.error("获取授权详情失败: " + e.getMessage());
        }
    }

    /**
     * 获取权限设置及记录类型
     */
    @GetMapping("/{authorizationId}/permissions")
    public Result getPermissionSettings(@PathVariable Integer authorizationId) {
        try {
            Map<String, Object> response = new HashMap<>();
            response.put("permissions", authorizeService.getPermissionSettings(authorizationId));
            response.put("recordTypes", authorizeService.getRecordTypeByAuthorizationId(authorizationId));
            System.out.println("permissions: "+response);
            return Result.success(response);
        } catch (Exception e) {
            log.error("获取权限设置失败", e);
            return Result.error("获取权限设置失败: " + e.getMessage());
        }
    }

    /**
     * 更新权限设置
     */
    @PutMapping("/{authorizationId}/permissions")
    public Result updatePermissionSettings(@PathVariable Integer authorizationId, @RequestBody Map<String, String> permissions) {
        try {
            authorizeService.updatePermissionSettings(authorizationId, permissions);
            return Result.success("权限设置更新成功");
        } catch (RuntimeException e) {
            log.error("更新权限设置失败", e);
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("更新权限设置异常", e);
            return Result.error("更新权限设置失败: " + e.getMessage());
        }
    }

    /**
     * 撤销授权
     */
    @DeleteMapping("/{authorizationId}")
    public ResponseEntity<?> deleteAuthorization(@PathVariable String authorizationId) {
        try {
            Integer id = Integer.parseInt(authorizationId);
            int rowsDeleted = authorizeService.deleteAuthorizationById(id);
            if (rowsDeleted > 0) {
                return ResponseEntity.ok().body("授权记录删除成功");
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (NumberFormatException e) {
            return ResponseEntity.badRequest().body("无效的授权ID格式: " + authorizationId);
        }
    }

    /**
     * 更新查看权限设置
     */
    @PostMapping("/look")
    public Result createLookPermission(@RequestBody AuthorizationLookRequest request) {
        // 生成新的授权ID（如果需要）
        Integer newAuthorizationId = null; // 可以根据业务逻辑生成或由数据库自增
        authorizeService.updateLookPermission(
                newAuthorizationId,
                request.getRecordType(),
                request.isLook()
        );
        return Result.success("授权记录创建成功");
    }

    @PatchMapping("/{authorizationId}/look")
    public Result updateLookPermission(
            @PathVariable Integer authorizationId,
            @RequestBody AuthorizationLookRequest request) {
        authorizeService.updateLookPermission(
                authorizationId,
                request.getRecordType(),
                request.isLook()
        );
        return Result.success(request);
    }

    /**
     * 创建修改权限记录
     */
    @PostMapping("/update")
    public Result createUpdatePermission(@RequestBody AuthorizationUpdateRequest request) {
        authorizeService.updateUpdatePermission(
                null,
                request.getRecordType(),
                request.isUpdate()
        );
        return Result.success("修改权限记录创建成功");
    }

    /**
     * 更新修改权限设置
     */
    @PatchMapping("/{authorizationId}/update")
    public Result updateUpdatePermission(
            @PathVariable Integer authorizationId,
            @RequestBody AuthorizationUpdateRequest request) {
        authorizeService.updateUpdatePermission(
                authorizationId,
                request.getRecordType(),
                request.isUpdate()
        );
        return Result.success(request);
    }

    /**
     * 创建删除权限记录
     */
    @PostMapping("/delete")
    public Result createDeletePermission(@RequestBody AuthorizationDeleteRequest request) {
        authorizeService.updateDeletePermission(
                null,
                request.getRecordType(),
                true
        );
        return Result.success("删除权限记录创建成功");
    }

    /**
     * 更新删除权限设置
     */
    @PatchMapping("/{authorizationId}/delete")
    public Result updateDeletePermission(
            @PathVariable Integer authorizationId,
            @RequestBody AuthorizationDeleteRequest request) {
        authorizeService.updateDeletePermission(
                authorizationId,
                request.getRecordType(),
                request.isDelete()
        );
        System.out.println("delete:"+request.isDelete());
        return Result.success(request);
    }
}
